package cn.edu.ctbu.yrx.api;

import cn.edu.ctbu.yrx.constant.REnum;
import cn.edu.ctbu.yrx.dao.StudentRepository;
import cn.edu.ctbu.yrx.entity.CourseScore;
import cn.edu.ctbu.yrx.entity.Student;
import cn.edu.ctbu.yrx.entity.Teacher;
import cn.edu.ctbu.yrx.rexception.RException;
import cn.edu.ctbu.yrx.service.CourseScoreService;
import cn.edu.ctbu.yrx.service.StudentService;
import cn.edu.ctbu.yrx.util.RUtil;
import cn.edu.ctbu.yrx.vo.QueryObj;
import cn.edu.ctbu.yrx.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api/admin/student")
public class StudentApiController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private CourseScoreService courseScoreService;


    @GetMapping("/list")
    public R<List<Student>> findALL() {
        List<Student> students = studentService.getAll();
        return RUtil.success(students);
    }

    @GetMapping("{id}")
    public R<Student> findById(@PathVariable int id) {

        Student student = studentService.findById(id);
        return RUtil.success(student);
    }

    @GetMapping("/getByUserId")
    public R getByUserId(@RequestParam Integer userId) {
        Student student = studentRepository.findByUserId(userId);
        Integer studentId = student.getStuId();
        if (studentId == null) {
            return RUtil.fail("未找到教师信息");
        }
        return RUtil.success(studentId);
    }

    @PostMapping("/add")
    public R<Student> add(@RequestBody Student student) {
        return RUtil.success(studentService.add(student));
    }

    @PutMapping("/update")
    public R<Student> update(@RequestBody Student student) {
        return RUtil.success(studentService.update(student));
    }

//    @DeleteMapping("/delete/{id}")
//    public R delete(@PathVariable Integer id) {
//        studentService.delete(id);
//        return RUtil.success();
//    }

    //更改删除操作的连接
    @DeleteMapping("/deletebatch")
    public R delete(@RequestBody Iterable<Integer> ids) {
        studentService.deletebatch(ids);
        return RUtil.success();
    }

//    @GetMapping("/validateUser")
//    public R validateUsernameAndPassword(String username, String password, HttpServletRequest request) throws Exception {
//        User user = studentService.validateUsernameAndPassword(username, password);
//
//        request.getSession().setAttribute("userInfo", user);
//        return RUtil.success();
//    }

    //    @PostMapping("/getbypage")
//    public R<Page<Student>> getByPage(@RequestBody QueryObj<Student> qObj) {
//        Sort sort = Sort.by(Sort.Direction.DESC, "id");
//        Integer pageIndex = 0;
//        Integer pageSize = 10;
//
//        if (qObj == null) {
//            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
//            Page<Student> students = studentService.getAll(pageable);
//            return RUtil.success(students.getContent(), students.getTotalElements());
//        } else {
//            pageIndex = qObj.getPage() - 1;
//            pageSize = qObj.getLimit();
//
//            if (qObj.getData() instanceof Student) {
//                Student student = (Student) qObj.getData();
//                Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
//
//                ExampleMatcher matcher = ExampleMatcher.matching()
//                        .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
//                        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //添加一个姓名模糊匹配
//                        .withIgnoreNullValues();
//
//                Example<Student> example = Example.of(student, matcher);
//                Page<Student> studentPage = studentService.getAll(example, pageable);
//                return RUtil.success(studentPage.getContent(), studentPage.getTotalElements());
//            } else {
//                throw new RException(REnum.QUERY_ERR);
//            }
//        }
//
//
//    }
    @PostMapping("/getbypage")
    public R<Page<CourseScore>> getByPage(@RequestBody QueryObj<CourseScore> qObj) {
        Sort sort = Sort.by(Sort.Direction.DESC, "courseId");
        Integer pageIndex = 0;
        Integer pageSize = 10;

        log.info("接收到的参数: {}", qObj);
        if (qObj == null) {
            return RUtil.error(REnum.PARAM_ERROR); // 参数错误，返回错误响应
        } else {
            pageIndex = qObj.getPage() - 1;
            pageSize = qObj.getLimit();
            Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

            // 获取studentId，若为null则返回错误
            Integer studentId = null;
            if (qObj.getData() != null && qObj.getData().getStudent() != null) {
                studentId = qObj.getData().getStudent().getStuId();
                System.out.println("提取的学生ID: " + studentId);
            }

            if (studentId == null || studentId <= 0) {
                return RUtil.error(REnum.STUDENT_ID_REQUIRED); // 学生ID不能为空或无效
            }

            // 验证学生ID是否存在
            Student student = studentService.getById(studentId);
            if (student == null) {
                return RUtil.error(REnum.STUDENT_NOT_FOUND); // 学生不存在
            }

            Page<CourseScore> page = courseScoreService.findByStudentStuId(studentId, pageable);
            return RUtil.success(page.getContent(), page.getTotalElements());
        }
    }


}
